package com.chainyoung.component_tmperson.ui.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chainyoung.common.base.BaseActivity;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.utils.AppUtils;
import com.chainyoung.common.utils.ToastUtil;
import com.chainyoung.component_tmperson.R;
import com.chainyoung.component_tmperson.R2;
import com.chainyoung.component_tmperson.qrcodeview.QRCodeView;
import com.chainyoung.component_tmperson.zxing.Result;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zxing.UriUtils;
import com.zxing.activity.CodeUtils;
import com.zxing.activity.ScanActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.functions.Consumer;


public class ScanQrCodeActivity extends BaseActivity {


    @BindView(R2.id.qr_code_view)
    QRCodeView qrCodeView;

    private CodeUtils.AnalyzeCallback mCallback;
    private static final int REQ_CAMERA = 0x101;
    private static final int REQ_PHOTO = 0x102;

    private List<String> selectImgs = new ArrayList<>();


    @Override
    protected void setupActivityComponent(AppComponent appComponent) {

    }

    @Override
    protected void initUI() {
        setCurrentTitle(getString(R.string.tmperson_scan_code));
        showAndSetBarRightText("相册");
        //checkCameraPermission();
        qrCodeView.setOnQRCodeListener(new QRCodeView.OnQRCodeRecognitionListener() {
            @Override
            public void onQRCodeRecognition(Result result) {
                Intent intent = new Intent();
                intent.putExtra("data", result.getText());
                setResult(RESULT_OK, intent);
                finish();
            }
        });

        mCallback = new CodeUtils.AnalyzeCallback() {
            @Override
            public void onAnalyzeSuccess(Bitmap mBitmap, String result) {
                Intent intent = new Intent();
                intent.putExtra("data", result);
                setResult(RESULT_OK, intent);
                finish();
            }

            @Override
            public void onAnalyzeFailed() {
//                Intent intent= new Intent();
//                Bundle bundle = new Bundle();
//                bundle.putInt(CodeUtils.RESULT_TYPE,CodeUtils.RESULT_FAILED);
//                intent.putExtras(bundle);
//                setResult(RESULT_OK,intent);
//                finish();
                ToastUtil.showToast("扫描失败");
            }
        };
        new RxPermissions(this).request(Manifest.permission.CAMERA)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(@io.reactivex.annotations.NonNull Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            if (cameraIsCanUse()) {
                                if (qrCodeView != null) {
                                    qrCodeView.startPreview();
                                }
                            } else {
                                ToastUtil.showToast(getString(R.string.pls_granted_camera_permissions));
                                finish();
                                return;
                            }
                        } else {
                            ToastUtil.showToast(getString(R.string.pls_granted_permissions));
                            finish();
                            return;
                        }
                    }
                });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQ_CHOOSE_PHOTO:
                if (resultCode == RESULT_OK) {
                    String path = "";
                    Uri uri = data.getData();
                    try {
                        path = UriUtils.getPath(getApplicationContext(), uri);
                        CodeUtils.analyzeBitmap(path, mCallback);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case PictureConfig.CHOOSE_REQUEST:
                // 图片选择结果回调
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                // 例如 LocalMedia 里面返回三种path
                // 1.media.getPath(); 为原图path
                // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                selectImgs.clear();
                for (LocalMedia media : selectList) {
                    selectImgs.add(media.getCompressPath());
                    Log.i("图片-----》", media.getCompressPath());
                }
                try {
                    CodeUtils.analyzeBitmap(selectImgs.get(0), mCallback);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
    }

    private static final int REQ_CHOOSE_PHOTO = 0x103;

    @Override
    public void onRightTxtClicked(View v) {
        super.onRightTxtClicked(v);
        new RxPermissions(this).request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(@io.reactivex.annotations.NonNull Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            choosePhoto();
                        } else {
                            ToastUtil.showToast(getString(R.string.pls_granted_permissions));
                        }
                    }
                });
        //checkAlbumPermission();
    }

    /**
     * 跳转相册选择
     */
    private void choosePhoto() {
        /*Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, REQ_CHOOSE_PHOTO);*/

        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .maxSelectNum(1)
                .enableCrop(true)
                .glideOverride(400, 400)
                .compress(true)
                .compressSavePath(AppUtils.getImagePath())
                .freeStyleCropEnabled(true)
                .minimumCompressSize(100)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }


    @Override
    protected void initData() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.tmperson_activity_scan;
    }


    @Override
    protected void onResume() {
        super.onResume();

        //checkCameraPermission();
    }

    @Override
    protected void onPause() {
        qrCodeView.stopPreview();
        super.onPause();
    }


    /**
     * 检查相机权限
     */
    @TargetApi(23)
    private void checkCameraPermission() {
        int code = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
        if (code == PackageManager.PERMISSION_GRANTED) {
            return;
        }
        if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
            Toast.makeText(getApplication(), "拒绝此权限将导致功能不可用！", Toast.LENGTH_SHORT).show();
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQ_CAMERA);
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQ_CAMERA);
        }
    }

    /**
     * 查看相册权限
     */
    @TargetApi(23)
    private void checkAlbumPermission() {
        int code = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (code == PackageManager.PERMISSION_GRANTED) {
            choosePhoto();
            return;
        }
        if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            Toast.makeText(getApplication(), "拒绝此权限将导致功能不可用！", Toast.LENGTH_SHORT).show();
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQ_PHOTO);
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQ_PHOTO);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQ_CAMERA:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    qrCodeView.startPreview();
                }
                break;
            case REQ_PHOTO:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    choosePhoto();
                }
                break;
            default:
                break;
        }
    }

    public static boolean cameraIsCanUse() {
        boolean isCanUse = true;
        Camera mCamera = null;
        try {
            mCamera = Camera.open();
            Camera.Parameters mParameters = mCamera.getParameters();
            mCamera.setParameters(mParameters);
        } catch (Exception e) {
            isCanUse = false;
        }

        if (mCamera != null) {
            try {
                mCamera.release();
            } catch (Exception e) {
                e.printStackTrace();
                return isCanUse;
            }
        }
        return isCanUse;
    }


}
